﻿using S2.Models;
using S2.Services;
using S2.Services.Models;
using System.IO;
using System.Web;
using System;
using System.Web.Http;
using System.Collections.Generic;
using System.Reflection;
using System.Linq;

namespace S2.Controllers
{
    public class EndpointsController : ApiController
    {
        [HttpGet]
        [Route("api/generate-endpoints")]
        public IHttpActionResult GenerateEndpoints()
        {
            var endpoints = GetApiEndpoints();
            var filePath = HttpContext.Current.Server.MapPath("~/App_Data/endpoints.txt");

            try
            {
                File.WriteAllLines(filePath, endpoints);
                return Ok("端点文件已生成: " + filePath);
            }
            catch (Exception ex)
            {
                return InternalServerError(ex);
            }
        }

        private List<string> GetApiEndpoints()
        {
            var endpoints = new List<string>();
            var controllers = Assembly.GetExecutingAssembly().GetTypes()
                .Where(type => typeof(ApiController).IsAssignableFrom(type)).ToList();

            foreach (var controller in controllers)
            {
                var methods = controller.GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly)
                    .Where(m => m.GetCustomAttributes<HttpGetAttribute>().Any() ||
                                m.GetCustomAttributes<HttpPostAttribute>().Any() ||
                                m.GetCustomAttributes<HttpPutAttribute>().Any() ||
                                m.GetCustomAttributes<HttpDeleteAttribute>().Any());

                foreach (var method in methods)
                {
                    var routeAttributes = method.GetCustomAttributes<RouteAttribute>();
                    foreach (var routeAttribute in routeAttributes)
                    {
                        endpoints.Add($"{method.Name} - {routeAttribute.Template}");
                    }
                }
            }

            return endpoints;
        }
    }
}
